package com.tianqu.tms.www.rental.controller;

import java.sql.Timestamp;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.entity.RentalLocationInfo;
import com.tianqu.tms.www.rental.actionform.RentalContractAddInputForm;
import com.tianqu.tms.www.rental.viewhelper.RentalContractAddInputViewHelper;

/**
 * 合同中止 - 信息查看 controller
 * @author mufeiyu
 */
public class RentalContractBreakResultController extends TmsController {
	private Logger logger = Logger.getLogger(RentalContractBreakResultController.class);
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			RentalContractAddInputForm rentalForm = (RentalContractAddInputForm) uc.getInputForm();
			RentalContractAddInputViewHelper view = (RentalContractAddInputViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
			
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();

			TmsUserProfile profile = uc.getUserProfile();			
			String updataTime = DateUtil.getCurrentTime();
			contractInfo.setId(view.getId());
			contractInfo.setStatus(5);
			contractInfo.setSerial(view.getSerial());
			contractInfo.setUpdateUserId(profile.getUniqueId());		
			contractInfo.setUpdateTime(Timestamp.valueOf(updataTime));
			//更新合同状态
			contractInfo.updateContractStatus(contractInfo);

			// 插入 租赁合同操作记录表
			contractInfo.setHandleType(4);//4：合同终止
			contractInfo.setRemark(java.net.URLDecoder.decode(uc.getParameter("remark"),"utf8"));//备注
			contractInfo.insertContractUpdateHistroy(contractInfo);
			
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
}
